from flask import Blueprint, jsonify, request, json
from R_CMgmt.riskCopeOperation import copeTestOprt

riskCopeTest = Blueprint('riskCopeTest', __name__)


@riskCopeTest.route('/copeTestIndex', methods=['GET'])
def copeTestsIndex():
    return "1"


@riskCopeTest.route('/init', methods=['GET'])
def init():
    json_str = copeTestOprt.getAllCopeTest()
    if json_str == 0:
        return json_str

    return jsonify(json_str)


@riskCopeTest.route('/getRiskForTest', methods=['GET'])
def getRiskForTest():
    json_str = copeTestOprt.getRiskForTestFromDB()
    if json_str == 0:
        return json_str

    return jsonify(json_str)


@riskCopeTest.route('/getStaffForTest', methods=['GET'])
def getStaffForTest():
    json_str = copeTestOprt.getStaffForTestFromDB()
    if json_str == 0:
        return json_str

    return jsonify(json_str)


@riskCopeTest.route('/addRiskCopeTest', methods=['POST'])
def addRiskCopeTest():
    print("new a RiskCopeTest")
    data = request.get_data()
    print(data)
    json_data = json.loads(data.decode("utf-8"))
    print(json_data)

    if copeTestOprt.addRiskCopeTestToDB(json_data.get('risk_cope_id'), json_data.get('operation')):
        return jsonify(1)
    else:
        return jsonify(2)


@riskCopeTest.route('/select', methods=['POST'])
def copeRecordVagueSelect():
    data = request.get_data()
    json_data = json.loads(data.decode("utf-8"))
    word = json_data.get('word')

    json_str = copeTestOprt.searchCopeTest(word)
    if json_str == 0:
        return json_str

    return jsonify(json_str)


@riskCopeTest.route('/delete', methods=['POST'])
def deleteCopeRecord():
    data = request.get_data()
    print(data)
    json_data = json.loads(data.decode("utf-8"))
    print(json_data)

    if copeTestOprt.deleteCopeTestFromDB(json_data.get('risk_cope_record_id')):
        return jsonify(1)
    else:
        return jsonify(2)


@riskCopeTest.route('/updateStatusInRiskCope', methods=['POST'])
def updateStatusInRiskCope():
    data = request.get_data()
    print(data)
    json_data = json.loads(data.decode("utf-8"))
    print(json_data)

    if copeTestOprt.updateStatusInRiskCopeFromDB(json_data.get('status'), json_data.get('risk_cope_id'))\
            and copeTestOprt.updateStatusInRiskCopeRecordFromDB(json_data.get('risk_cope_record_id')):
        return jsonify(1)
    else:
        return jsonify(2)


@riskCopeTest.route('/getCopeRecordWithCopeID', methods=['POST'])
def getCopeRecordWithCopeID():
    data = request.get_data()
    json_data = json.loads(data.decode("utf-8"))
    risk_cope_id = json_data.get('risk_cope_id')

    json_str = copeTestOprt.getCopeRecordWithCopeIDFromDB(risk_cope_id)
    if json_str == 0:
        return json_str

    return jsonify(json_str)

